// Copyright (C) Kumo inc. and its affiliates.
// Author: Jeff.li lijippy@163.com
// All rights reserved.
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published
// by the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program.  If not, see <https://www.gnu.org/licenses/>.
//


#include <pollux/common/base/admission_controller.h>

#include <pollux/common/base/exceptions.h>
#include <pollux/common/base/stats_reporter.h>
#include <pollux/common/time/timer.h>

namespace kumo::pollux::common {
    void AdmissionController::accept(uint64_t resourceUnits) {
        ContinueFuture future;
        uint64_t updatedValue = 0;
        POLLUX_CHECK_LE(
            resourceUnits,
            config_.maxLimit,
            "A single request cannot exceed the max limit"); {
            std::lock_guard<std::mutex> l(mu_);
            if (unitsUsed_ + resourceUnits > config_.maxLimit) {
                auto [unblockPromise, unblockFuture] = makePolluxContinuePromiseContract();
                Request req;
                req.unitsRequested = resourceUnits;
                req.promise = std::move(unblockPromise);
                queue_.push_back(std::move(req));
                future = std::move(unblockFuture);
            } else {
                updatedValue = unitsUsed_ += resourceUnits;
            }
        }
        if (!future.valid()) {
            // Only upadate if there was no wait, as the releasing thread is responsible
            // for updating the metric.
            if (!config_.resourceUsageAvgMetric.empty()) {
                RECORD_METRIC_VALUE(config_.resourceUsageAvgMetric, updatedValue);
            }
            return;
        }
        if (!config_.resourceQueuedCountMetric.empty()) {
            RECORD_METRIC_VALUE(config_.resourceQueuedCountMetric);
        }
        uint64_t waitTimeUs{0}; {
            MicrosecondTimer timer(&waitTimeUs);
            future.wait();
        }
        if (!config_.resourceQueuedTimeMsHistogramMetric.empty()) {
            RECORD_HISTOGRAM_METRIC_VALUE(
                config_.resourceQueuedTimeMsHistogramMetric, waitTimeUs / 1'000);
        }
    }

    void AdmissionController::release(uint64_t resourceUnits) {
        uint64_t updatedValue = 0; {
            std::lock_guard<std::mutex> l(mu_);
            POLLUX_CHECK_LE(
                resourceUnits,
                unitsUsed_,
                "Cannot release more units than have been acquired");
            unitsUsed_ -= resourceUnits;
            while (!queue_.empty()) {
                auto &request = queue_.front();
                if (unitsUsed_ + request.unitsRequested > config_.maxLimit) {
                    break;
                }
                unitsUsed_ += request.unitsRequested;
                request.promise.setValue();
                queue_.pop_front();
            }
            updatedValue = unitsUsed_;
        }
        if (!config_.resourceUsageAvgMetric.empty()) {
            RECORD_METRIC_VALUE(config_.resourceUsageAvgMetric, updatedValue);
        }
    }
} // namespace kumo::pollux::common
